'use strict';

var app = angular.module('fireProtectionApp')
    .config(function(cfpLoadingBarProvider) {
        cfpLoadingBarProvider.includeSpinner = true;
    })


    .service('dataService', ['$http', '$rootScope', function ($http, $rootScope) {

    this.appVo = new AppVO();

    /* F4 Help */
    this.getF4Help = function (iobjnm, vname, queryName) {
        var param = {
            iobjnm: iobjnm,
            vname: vname,
            queryName:queryName
        };
        return   $http({method: this.appVo.METHOD, url: this.appVo.BSP_GET_F4_URL , params: param});
    }

    this.getVarList = function(queryName) {
        var param = {
            rep_id: queryName
        };
        return  $http({method: this.appVo.METHOD, url: this.appVo.BSP_QUERY_VARS_LIST_URL, params: param});
    }

    /* F4 Help */
    this.executeQuery = function(param)
    {
        //  var param = {query: queryName};
        return $http({method: this.appVo.METHOD, url: this.appVo.BSP_QUERY_EXECUTE_URL, params: param});
    }

    this.getOrgTree = function(param)
    {
        var param = {};
        return $http({method: this.appVo.METHOD, url: this.appVo.BSP_ORG_TREE_URL});
    }

    $rootScope.$on('TREE_NODE_SELECTED_EVENT', function(event, data){
        $rootScope.$broadcast("EXECUTE_REPORT_EVENT",  data);
    });

    $rootScope.$on('YEAR_HAS_BEEN_SELECTED_EVENT', function(event, data){
        $rootScope.$broadcast("EXECUTE_REPORT_EVENT",  data);
    });

    $rootScope.$on('QUARTER_HAS_BEEN_SELECTED_EVENT', function(event, data){
        $rootScope.$broadcast("EXECUTE_REPORT_EVENT",  data);
    });

    $rootScope.$on('SET_DEFAULT_YEAR_QUARTER_EVENT', function(event, data){
        $rootScope.$broadcast("UPDATE_DEFAULT_YEAR_QUARTER_EVENT",  data);
    });





}])
    .service('mockHelperService', [function ($rootScope) {

    this.generateReportVariableParam = function(query, org, year, quarter) {
        var result = {};
        var counter = 1;
        var tmp = '';
        if(quarter != '')
        {
            tmp += '&VAR_NAME_' + counter + '=' + 'ZCOQUAR2';
            tmp += '&VAR_VALUE_EXT_' + counter + '=' + quarter;
            counter++;
        }

        if(org != "")
        {
            tmp += '&VAR_NAME_' + counter + '=' + 'ZEHORGH';
            tmp += '&VAR_VALUE_EXT_' + counter + '=' + org;
            tmp += '&VAR_NODE_IOBJNM_' + counter + '=' + '';
            counter++;
        }

        if(year != '')
        {
            tmp += '&VAR_NAME_' + counter + '=' + 'ZEH_FI_YEAR';
            tmp += '&VAR_VALUE_EXT_' + counter + '=' + year;
        }

        result['variables'] = encodeURI(tmp);
        result['query'] = query;


        return result;
    } }])

    .controller('MainCtrl', function ($scope, dataService, $timeout, cfpLoadingBar) {

        /* Show Loading Bar */
        $scope.start = function() {
            cfpLoadingBar.start();
        };
        /* Hide Loading Bar */
        $scope.complete = function () {
            cfpLoadingBar.complete();
        }

        /* HTTP: OK -- Parse: OK */
        $scope.executeQuery = function(queryName, variables) {
            //Show Loading Bar
            $scope.start();

            dataService.executeQuery(queryName, variables)
                .success(function (data) {
                    $scope.complete();
                    $timeout(function() {
                        $scope.complete();
                    }, 1000);

                    $scope.status = status;
                    $scope.data  =  data;
                    $scope.reportVo = (new ReportVO(data)).parse();

                })
                .error(function (error) {
                    //Stop loading Bar
                    $scope.complete();
                    $scope.status = 'Unable to load query data: ' + error.message;
                    $scope.data = data;
                });
        };


        /* HTTP: OK -- Parse: OK */
        $scope.getF4Help = function (iobjnm, vname, queryName) {
            dataService.getF4Help(iobjnm, vname, queryName).
                success(function(data, status) {
                    $scope.status = status;
                    $scope.data = $.xml2json(data);
                    $scope.varList = new F4VOList($scope.data);
                }).
                error(function(data, status) {
                    $scope.data = data || "Request failed";
                    $scope.status = status;
                });

        };

        /* Ok*/
        $scope.getVarList = function (queryName) {
            dataService.getVarList(queryName).
                success(function(data, status) {
                    $scope.status = status;
                    $scope.data = $.xml2json(data);
                }).
                error(function(data, status) {
                    $scope.data = data || "Request failed";
                    $scope.status = status;
                });

        };


        $scope.getOrgTree = function () {
            dataService.getOrgTree().
                success(function(data, status) {
                    $scope.status = status;
                    $scope.data = data;
                }).
                error(function(data, status) {
                    $scope.data = data || "Request failed";
                    $scope.status = status;
                });

        };


    })


    .controller('TreeCtrl', ['$scope','$rootScope', 'dataService', function ($scope,$rootScope, dataService) {
    $scope.searchText = "";
    $scope.selectedNode = "";
    $scope.$watch('selectedNode', function(newVal, oldVal) {
        console.log('selected node: ' + newVal);

    });
    $scope.dataProvider = [];

    /* Load Org Tree*/
    dataService.getOrgTree().
        success(function(data, status) {
            $scope.status = status;
            $scope.data = data;
            $scope.buildTree(data);
        }).
        error(function(data, status) {
            $scope.data = data || "Request failed";
            $scope.status = status;
        });


    $scope.buildTree = function(dataProvider)
    {
        $("#tree").fancytree({
            extensions: ["filter"],
            source:  dataProvider,

            filter: {
                mode: "hide"
            },
            activate: function(e, data) {

                var scope = angular.element('[ng-controller=TreeCtrl]').scope();
                scope.$apply(function(){
                    scope.selectedNode = data;

                    $rootScope.$broadcast("TREE_NODE_SELECTED_EVENT", {orgKey: data.node.key}) ;
                });
            },
            /*lazyload: function(e, data) {
             data.result = {url: "ajax-sub2.json"}
             },*/
            init: function(event, data) {
                //Expand the root node
                data.tree.getFirstChild().setExpanded();
            }

        });
        var tree = $("#tree").fancytree("getTree");
        $("input[name=search]").keyup(function(e){
            var match = $(this).val();
            if(e && e.which === $.ui.keyCode.ESCAPE || $.trim(match) === ""){
                $("button#btnResetSearch").click();
                return;
            }
            // Pass text as filter string (will be matched as substring in the node title)
            var n = tree.applyFilter(match);
            $("button#btnResetSearch").attr("disabled", false);
            $("span#matches").text("(" + n + " matches)");
        }).focus();
        $("button#btnResetSearch").click(function(e){
            $("input[name=search]").val("");
            $("span#matches").text("");
            tree.clearFilter();
        }).attr("disabled", true);
        $("input#hideMode").change(function(e){
            tree.options.filter.mode = $(this).is(":checked") ? "hide" : "dimm";
            tree.clearFilter();
            $("input[name=search]").keyup();
        });
    }

}])
    .controller('ControlBarCtrl', function($scope, $rootScope, dataService, $filter, ngTableParams){


        $scope.year = "2012";
        $scope.quarter = "1";

        $scope.$watch('quarter', function(newVal, oldVal) {
            $scope.radioModel = 'Q' + newVal;
        });


        /* GETTING Year List */
        dataService.getF4Help('0CALYEAR', 'ZEH_FI_YEAR', 'ZFIRE_PROTECTION_DEPT_KPI').
            success(function(data, status) {
                $scope.status = status;
                $scope.data = $.xml2json(data);
                $scope.yearList = new F4VOList($scope.data);

                /* Set Default Year */
                if($scope.yearList != 'undefined' && $scope.yearList.length > 1)
                {

                    initalizeYearGrid($scope.yearList, $scope.year);

                    //Sending updates to Main Controller
                    $scope.setDefaultYearQuarter($scope.year, $scope.quarter);


                    $scope.tableParams = new ngTableParams({
                        page: 1,            // show first page
                        count: 999999999999,          // count per page
                        filter: {
                            // name: 'M'       // initial filter
                        }
                    }, {
                        counts: [],
                        total: $scope.yearList.length, // length of data
                        getData: function($defer, params) {
                            // use build-in angular filter
                            var orderedData = params.filter() ?
                                $filter('filter')($scope.yearList , params.filter()) :
                                data;
                            $scope.users = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());
                            params.total(orderedData.length); // set total for recalc pagination
                            $defer.resolve($scope.users);
                        }
                    });
                }

            }).
            error(function(data, status) {
                $scope.data = data || "Request failed";
                $scope.status = status;
            });



        /* Year has been changed */
        $scope.setSelectedYear = function(year) {
            if(year != "")
            {
                $scope.year = year;
                $rootScope.$broadcast("YEAR_HAS_BEEN_SELECTED_EVENT", {quarter:  $scope.quarter, year: $scope.year}) ;
            }
        }

        /* Quarter has been changed */
        $scope.setSelectedQuarter = function(item, $event){
            var selectedQuarter = $($event.target).val();
            if(selectedQuarter !== $scope.quarter)
            {
                $scope.quarter  = selectedQuarter;
                $rootScope.$broadcast("QUARTER_HAS_BEEN_SELECTED_EVENT", {quarter:  $scope.quarter, year: $scope.year}) ;
            }
        }

        /* Set Default Year  and Quarter */
        $scope.setDefaultYearQuarter = function(year, quarter) {
            $rootScope.$broadcast("SET_DEFAULT_YEAR_QUARTER_EVENT", {quarter:  $scope.quarter, year: $scope.year}) ;
        }


        $('.dropdown-menu').find('form').click(function (e) {
            e.stopPropagation();
        });


        /* User Clicks on Save Button */
        $scope.changeYearSelection  = function (data)
        {
            //Clear Selections
            for(var i = 0; i < this.tableParams.data.length; i++)
            {
                if(this.tableParams.data[i].$selected)
                    this.tableParams.data[i].$selected = false;
            }
            $scope.tempSelctedYear = data.key;
        }

        /* User Clicks on Cancel Button */
        $scope.cancelYearSelection = function(data)
        {
            $scope.tempSelctedYear = "";
            initalizeYearGrid($scope.yearList, $scope.year);
        }

        $scope.tempSelctedYear = "";


            var initalizeYearGrid = function (dataList, defaultYear)
            {
                for(var i = 0; i < dataList.length; i++)
                {
                    if(defaultYear == dataList[i].key)
                        dataList[i]['$selected'] = true;
                    else
                        dataList[i]['$selected'] = false;
                }
            }


    })
    .controller('tablectrl', function($scope, $rootScope, $filter, Report, AppSetting,  ngTableParams,
                                      dataService, toaster, mockHelperService) {

        $scope.year = "";
        $scope.quarter = "";
        $scope.orgKey = "";
        $scope.showOrgKey = false;

        $scope.clearRows = function() {
            $scope.rows = [];
        }




        $scope.$on('UPDATE_DEFAULT_YEAR_QUARTER_EVENT', function(event, data){
            $scope.year = data.year;
            $scope.quarter = data.quarter;

            //Auto Execute Query
            var param = mockHelperService.generateReportVariableParam('ZCFIREP/ZFIRE_PROTECTION_DEPT_KPI',
                $scope.orgKey, $scope.year, $scope.quarter);
            executeQuery(param);
        });

        $scope.$on('EXECUTE_REPORT_EVENT', function(event, data){

            if(data != 'undefined')
            {
                if(data.hasOwnProperty('year'))
                    $scope.year = data.year;
                if(data.hasOwnProperty('quarter'))
                    $scope.quarter = data.quarter;
                if(data.hasOwnProperty('orgKey'))
                    $scope.orgKey = data.orgKey;
            }

            var param = mockHelperService.generateReportVariableParam('ZCFIREP/ZFIRE_PROTECTION_DEPT_KPI',
                $scope.orgKey, $scope.year, $scope.quarter);

            $scope.rows = [];
            $scope.groupsList = [];

            $scope.clearRows();
            executeQuery(param);
        });


        $scope.rows = [];
        $scope.groupsList = [];
        $scope.groupby = 'ZFIRCOMP';//'ZEHFIRKPI__ZEHFIRKPI_KEY';


        /* Executing Query */
        var executeQuery = function(param)
        {
            dataService.executeQuery(param)
                .success(function (data) {
                    $scope.status = status;
                    $scope.data  =  data;

                    if($scope.orgKey != "")
                        $scope.showOrgKey = true;
                    else
                        $scope.showOrgKey = false;

                    var reportVo = new ReportVO(data);
                    reportVo.parse();
                    $scope.reportVo = reportVo;


                    $scope.rows = $scope.reportVo.rows ;

                    toaster.pop('success', "Query", $scope.rows.length + ' records has been loaded', null, 'trustedHtml');

                    $scope.groupsList = $scope.reportVo.groupedList;


                    $scope.$watch('rows', function(newVal, oldVal) {
                        console.log(newVal !== oldVal);

                        //dinamic grouping
                        $scope.tableParams = new ngTableParams({
                            page: 1,            // show first page
                            count: -1        // count per page

                        }, {
                            counts: [], // hide page counts control
                            groupBy: $scope.groupby,
                            total: function () { return $scope.rows.length; }, // length of data
                            getData: function($defer, params) {
                                var orderedData = params.sorting() ?
                                    $filter('orderBy')($scope.rows, $scope.tableParams.orderBy()) :   $scope.rows;

                                $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                            }
                        });
                    });





                })
                .error(function (error) {
                    $scope.status = 'Unable to load query data: ' + error.message;
                    $scope.data = data;
                    toaster.pop('error', "Query", 'Unable to load query data: ' + error.message, null, 'trustedHtml');
                });



        }




        $scope.getGroupText = function(id, groupsList) {
            var listLength = groupsList.length;

            for (var i = 0; i < groupsList.length; i++) {
                if(id == groupsList[i].id)
                {
                    return groupsList[i].text;
                    break;
                }
            }
        }

        $scope.getGroupValue = function(id, groupsList) {
            var listLength = groupsList.length;

            for (var i = 0; i < groupsList.length; i++) {
                if(id == groupsList[i].id)
                {
                    return groupsList[i].value;
                    break;
                }
            }
        }
        $scope.checkIfOrgSelected = function() {
            if($scope.orgKey == '')
                return false;
            else
                return true;
        }
    })
    .controller('EquationsController', function($scope){
        $('#list').click(function(event){event.preventDefault();$('#products .item').addClass('list-group-item');});
        $('#grid').click(function(event){event.preventDefault();$('#products .item').removeClass('list-group-item');$('#products .item').addClass('grid-group-item');});
    })

    .controller('ThemeController', function($scope){
        $scope.colorsList		=
            [{ title:"Pale Worm Brown", bgColor:"rgb(198, 156, 109)", class:"", color:"#c69c6d" },
                { title:"Medium Warm Brown", bgColor:"rgb(140, 98, 57)", class:"", color:"#8c6239" },
                { title:"Pale Cool Brown", bgColor:"rgb(199, 178, 153)", class:"", color:"#c7b299" },
                { title:"Pure Cyan", bgColor:"rgb(102, 199, 235)", class:"", color:"rgb(102, 199, 235)"},
                { title:"Pure Green", bgColor:"rgb(0, 166, 81)", class:"", color:"#00a651"},
                { title:"Pure Green Cyan", bgColor:"rgb(0, 169, 157)", class:"", color:"#00a99d"},
                { title:"Pure Pea Green", bgColor:"rgb(141, 198, 63)", class:"", color:"#8dc63f"},
                { title:"Orange", bgColor:"rgb(241, 176, 72)", class:"", color:"rgb(241, 176, 72)"},
                { title:"Light Red", bgColor:"rgb(219, 124, 128)", class:"", color:"rgb(219, 124, 128)"},
                { title:"Light Violet", bgColor:"rgb(166, 164, 202)", class:"", color:"#A6A4CA"},
                { title:"Grey 5%", bgColor:"rgb(245, 245, 245)", class:"light", color:"rgb(245,245,245)"},
                { title:"Grey 20%", bgColor:"rgb(215, 215, 215)", class:"light", color:"rgb(215, 215, 215)"},
                { title:"Grey 40%", bgColor:"rgb(172, 172, 172)", class:"", color:"rgb(172, 172, 172)"},
                { title:"Grey 60%", bgColor:"rgb(125, 125, 125)", class:"", color:"rgb(125, 125, 125)"},
                { title:"Grey 70%", bgColor:"rgb(99, 99, 99)", class:"", color:"rgb(99, 99, 99)"},
                { title:"Grey 80%", bgColor:"rgb(70, 70, 70)", class:"", color:"rgb(70, 70, 70)"},
                { title:"Grey 85%", bgColor:"rgb(54, 54, 54)", class:"", color:"rgb(54, 54, 54)"},
                { title:"Grey 90%", bgColor:"rgb(37, 37, 37)", class:"", color:"rgb(37, 37, 37)"}];

        $scope.setBackgroundColor = function(color) {
            return {'background-color': color}
        }

        $scope.setBackGroundColor = function(colorList) {
            $('body').css("background-color", colorList.color);
            if(color.class == "light")
            {
          //      $('body').css("color", "#000000");
            }

        }
    })


